package com.hzhh123.download;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.Util;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class LocationActivity extends AppCompatActivity {
    private static final String TAG = "LocationActivity";
    private DownloadTask task;
    private int REQUEST_CODE_EXTERNAL_STORAGE = 20;
    private ImageView start,pause,download;
    private TextView speed,size,totalSize,space,size_str,create_time;
    private ProgressBar progressBar;
    private TextView refresh;
    private int actionStatus=2;//1-开始 2-暂停
    private Callback.Cancelable handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        initUI();
        checkExtrnalStorage();
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                download.setVisibility(View.GONE);
                 download();
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // download();
                actionStatus=2;
                start.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                download();
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                download();
            }
        });
        //暂停
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                task.cancel();
                actionStatus=1;
                start.setVisibility(View.VISIBLE);
                pause.setVisibility(View.GONE);
//                handler.cancel();
            }
        });
    }


    private void download(){
        progressBar.setVisibility(View.VISIBLE);
        start.setVisibility(View.GONE);
        pause.setVisibility(View.VISIBLE);
        String filename = "TensorFlow.pdf";
        String url = "http://192.168.124.7:8090/TensorFlow.pdf";
        File parentFile = Environment.getExternalStorageDirectory();
//        File parentFile = getExternalCacheDir();
        task = new DownloadTask.Builder(url, parentFile)
                .setFilename(filename)
                .setMinIntervalMillisCallbackProcess(30) // 下载进度回调的间隔时间（毫秒）
                .setPassIfAlreadyCompleted(false)// 任务过去已完成是否要重新下载
                .setPriority(10)
                .build();
        task.setRedirectLocation(url);
        task.enqueue(new DownloadListener4WithSpeed() {
            @Override
            public void taskStart(@NonNull DownloadTask task) {
                Log.d(TAG, "taskStart: "+task.getId());
            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
                Log.d(TAG, "connectStart: ");
            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
                Log.d(TAG, "connectEnd: ");
            }

            @Override
            public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                Log.d(TAG, "infoReady: ");
            }

            @Override
            public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {
                Log.d(TAG, "progressBlock: ");
            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                Log.d(TAG, "progress: "+taskSpeed.speed());
                speed.setText(taskSpeed.speed());
                float percent=((float)task.getInfo().getTotalOffset()/task.getInfo().getTotalLength())*100;
                System.out.println((int)percent);
                size.setText(Util.humanReadableBytes(task.getInfo().getTotalLength(),true) +"("+(int)percent+"%)");
                progressBar.setProgress((int)percent);
            }

            @Override
            public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {
                Log.d(TAG, "blockEnd: ");
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                float percent=((float)task.getInfo().getTotalOffset()/task.getInfo().getTotalLength())*100;
                System.out.println((int)percent);
                System.out.println(cause==EndCause.CANCELED);
                if((int)percent==100){
                    String totalSize = Util.humanReadableBytes(task.getInfo().getTotalLength(), true).toString();
                    size.setText(totalSize +"("+(int)percent+"%)");
                    progressBar.setProgress((int)percent);
                    start.setVisibility(View.GONE);
                    pause.setVisibility(View.GONE);
                    download.setVisibility(View.GONE);
                    speed.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    space.setVisibility(View.VISIBLE);
                    size_str.setVisibility(View.VISIBLE);
                    create_time.setVisibility(View.VISIBLE);
                    size.setVisibility(View.GONE);
                    size_str.setText(totalSize);
                    create_time.setText(DateFormat.format("yyyy/MM/dd",new Date()));
                }
                Log.d(TAG, "cause: "+cause.toString());
                Log.d(TAG, "taskEnd: ");
                if(realCause!=null){
                    Log.d(TAG, "realCause: "+realCause.getMessage());
                }
            }
        });
    }

    //开始下载apk  网络请求使用的是xutils框架
    private void download1() {
        final long t1=System.currentTimeMillis();
        progressBar.setVisibility(View.VISIBLE);
       // String url = "http://192.168.124.7:8090/TensorFlow.pdf";
        String filename = "";
        String url = "https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk";
        RequestParams params = new RequestParams(url);
        String savePath = Environment.getExternalStorageDirectory() + "/20171108-111118.apk";
        //自定义保存路径，Environment.getExternalStorageDirectory()：SD卡的根目录
        params.setSaveFilePath(savePath);
        //设置是否可以立即取消下载
        params.setCancelFast(true);
        //设置是否自动根据头信息命名
        params.setAutoRename(false);
        //设置断点续传
        params.setAutoResume(true);
        handler = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File resultFile) {
                Toast.makeText(LocationActivity.this, "下载成功...", Toast.LENGTH_SHORT).show();
                size.setText("100%");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(LocationActivity.this, "下载失败...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                Log.d(TAG, "onFinished: ");
            }

            //网络请求之前回调
            @Override
            public void onWaiting() {
            }

            //网络请求开始的时候回调
            @Override
            public void onStarted() {

            }

            //下载的时候不断回调的方法
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                //当前进度和文件总大小
                // 当前的下载进度和文件总大小
                int percent = (int) (current * 100 / total);
                Log.d(TAG, "percent= " + percent);
                long t2=System.currentTimeMillis();
                String speed=""+current/(t2-t1);
                System.out.println(speed);
                size.setText(percent+"%");
                progressBar.setProgress(percent);
            }
        });
    }

    private void initUI(){
        refresh=findViewById(R.id.refresh);
        speed=findViewById(R.id.speed);
        size=findViewById(R.id.size);
        start=findViewById(R.id.start);
        pause=findViewById(R.id.pause);
        download=findViewById(R.id.download);
        create_time=findViewById(R.id.create_time);
        space=findViewById(R.id.space);
        size_str=findViewById(R.id.size_str);
        progressBar=findViewById(R.id.progressBar);
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 检查外部scard读写权限
     */
    private void checkExtrnalStorage(){
        //首先判断用户手机的版本号 如果版本大于6.0就需要动态申请权限
        //如果版本小于6.0就直接去扫描二维码
        if(Build.VERSION.SDK_INT>23){
            //说明是android6.0之前的
            //添加动态权限申请
            //1.定义一个数组，用来装载申请的权限
            String[] permissons={
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
            //2.判断这些权限有没有申请，没有申请的话，就把没有申请的权限放到一个数组里面
            ArrayList<String> deniedPermissions=new ArrayList<String>();
            for(String permission:permissons){
                int i = ContextCompat.checkSelfPermission(this, permission);
                if(PackageManager.PERMISSION_DENIED==i){
                    //说明权限没有被申请
                    deniedPermissions.add(permission);
                }
            }
            if(deniedPermissions.size()==0){
                //说明是android6.0之前的
                return;
            }
            //当你不知道数组多大的时候，就可以先创建一个集合，然后调用集合的toArray方法需要传递一个数组参数，这个数组参数的长度
            //设置成跟集合一样的长度
            String[] strings = deniedPermissions.toArray(new String[permissons.length]);
            //3.去申请权限
            ActivityCompat.requestPermissions(this,strings,REQUEST_CODE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
